package com.chookss.home.audit.clockIn;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.audit.adapter.ClockInRecordAdapter;
import com.chookss.home.entity.ClockInRecordEntity;
import com.chookss.home.gallery.CusTomDrawerPopupListener;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.BasisTimesUtils;
import com.google.gson.reflect.TypeToken;
import com.lvgroup.hospital.base.BaseAct;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupPosition;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

public class ClockInRecordActivity extends BaseAct {
//打卡 考勤记录列表

    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.common_right_txt)
    TextView common_right_txt;
    @BindView(R.id.rvView)
    RecyclerView recyclerView;
    @BindView(R.id.srlView)
    SmartRefreshLayout smrRf;
    private ClockInRecordAdapter adapter;
    private List<ClockInRecordEntity> list = new ArrayList<>();
    private int currentPage = 1;
    private int pageSize = 32;
    private boolean isEnd = false;//是否到底
    private View emptyView;
    private TextView tvNone;//空布局;
    private CustomClockInRecordPopupView drawerPopupView;
    private String dataMonth = "", dakaType = "";//筛选类型
    private String groupCode = "", employeeCode = "";//项目管理过来的查询个人考勤记录

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.common_srlview_top);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        commonTitleTxt.setText("考勤记录");
        groupCode=getIntent().getStringExtra("groupCode");
        employeeCode=getIntent().getStringExtra("employeeCode");
        if(Utils.isNull(groupCode)){
            common_right_txt.setText("筛选");
            common_right_txt.setVisibility(View.VISIBLE);
        }
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) smrRf.getLayoutParams();
        params.setMargins(0, Utils.dip2px(this, 12), 0, 0);
        smrRf.setLayoutParams(params);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new ClockInRecordAdapter(R.layout.item_clock_record, this, list);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        recyclerView.setAdapter(adapter);
        adapter.setGroupCode(groupCode);
        emptyView = LayoutInflater.from(this).inflate(R.layout.layout_common_empty, recyclerView, false);
        tvNone = emptyView.findViewById(R.id.tvEmpty);
        tvNone.setText("暂无数据");
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                getData();
            }
        });
        drawerPopupView = new CustomClockInRecordPopupView(this, new CusTomDrawerPopupListener() {
            @Override
            public void onListItemClick(int position, String data) {
                if (position == 0) {
                    choiceMonth();
                } else if (position == 1) {
                    //确定重新筛选
                    smrRf.autoRefresh();
                    drawerPopupView.dismiss();
                } else if (position == 2) {
                    //重置
                    monthS = "";
                    dakaType = "";
                } else if (position == 3) {
                    //类型
                    dakaType = data;
                }
            }
        });
        smrRf.autoRefresh();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        if (!Utils.isNull(dataMonth)) {
            map.put("month", dataMonth);
        }
        if (!Utils.isNull(dakaType)) {
            map.put("dakaType", dakaType);
        }
        String url="";
        if (Utils.isNull(groupCode)) {
            url=Urls.selectMyDakaList;
        }else{
            map.put("groupCode", groupCode);
            url=Urls.selectEmpDakaListForItem;
        }
        if (!Utils.isNull(employeeCode)) {
            map.put("employeeCode", employeeCode);
        }

        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<ClockInRecordEntity>>>() {
        }.getType(), null, url, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<ClockInRecordEntity>>() {
            @Override
            public void onSuccess(List<ClockInRecordEntity> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (smrRf == null) {
                    return;
                }
                if (data != null && data.size() > 0) {
                    if (data.size() < pageSize) {
                        isEnd = true;
                    }
                    int old = list.size();
                    list.addAll(data);
                    adapter.notifyItemRangeChanged(old, data.size());
                    smrRf.setVisibility(View.VISIBLE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        adapter.setEmptyView(emptyView);
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    String monthS = "";
    int mYear = 0, mMonth = 0, mDay = 0;

    private void choiceMonth() {
        Calendar calendar = Calendar.getInstance();
        if (mYear == 0) {
            mYear = calendar.get(Calendar.YEAR);
            mMonth = calendar.get(Calendar.MONTH);
            mDay = calendar.get(Calendar.DAY_OF_MONTH);
        }
        BasisTimesUtils.showDatePickerDialog(this, true, "请选择月份", mYear, mMonth, mDay,
                new BasisTimesUtils.OnDatePickerListener() {

                    @Override
                    public void onConfirm(int year, int month, int dayOfMonth) {
                        mYear = year;
                        mMonth = month - 1;
                        if (month > 9) {
                            monthS = month + "";
                        } else {
                            monthS = "0" + month;
                        }
                        dataMonth = mYear + monthS;
                        drawerPopupView.setData(0, mYear + "-" + monthS);
                    }

                    @Override
                    public void onCancel() {
                    }
                }).setDayGone();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();

        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("RefreshClockInRecord") || msg.equals("RefreshClockInManagerExamine")) {
                smrRf.autoRefresh();
            }
        }
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    @OnClick({R.id.common_title_back, R.id.common_right_txt})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.common_right_txt:
                new XPopup.Builder(this)
                        .isDestroyOnDismiss(true)
                        .popupPosition(PopupPosition.Right)//右边
                        .offsetY(Utils.getStatusBarHeight(this))
                        .asCustom(drawerPopupView)
                        .show();
                break;
        }
    }
}
